#include "StdAfx.h"
#include "CommandTemplate.h"

const TCHAR CCommandTemplate::chQuoteSpace[]  = _T("\" ");

CCommandTemplate::CCommandTemplate(const tstring& str)
{
	if (!str.empty())
	{
		tchar_it begin = str.begin();
		tchar_it it = str.begin();

		bool quoted = (*it == chQuote);

		if (quoted)
		{
			++begin;
			++it;
		}

		for (; it != str.end(); ++it)
		{
			if (( quoted && (*it == chQuote)) ||
				(!quoted && (*it == chSpace)))
			{
				break;
			}
		}

		tstring app(begin, it);

		TCHAR szExpanded[MAX_PATH];
		DWORD cchExpanded = ExpandEnvironmentStrings(app.c_str(), szExpanded, MAX_PATH);

		if (cchExpanded > 0)
		{
			m_App = tstring(szExpanded, cchExpanded-1);
			m_Params = tstring(it+1, str.end());
		}
	}
}

tstring CCommandTemplate::Process(const vector<tstring>& args) const
{
	tstringstream result;
	result << chQuote << m_App << chQuoteSpace;

	for (tchar_it it = m_Params.begin(); it != m_Params.end(); ++it)
	{
		if (*it != chPercent)
		{
			result.put(*it);
			continue;
		}

		if (++it == m_Params.end())
		{
			result.put(chPercent);
			break;
		}

		if (*it == chStar)
		{
			for (tstring_it a = args.begin(); a != args.end(); ++a)
			{
				result << chQuote << *a << chQuoteSpace;
			}
		}

		if (*it > chZero && *it <= chNine)
		{
			unsigned n = (*it - chZero) - 1;

			if (n < args.size())
			{
				result << chQuote << args.at(n) << chQuoteSpace;
			}
		}
	}

	return result.str();
}

